import { formatTime } from '../../utils/util';
Page({
    data: {
        list: [],
        loading: true,
        empty: true,
        finished: false,
        chooseAll: false, //底部全选
        totalPrice: 0, //选择价格总计
        checkNum: 0, //总选择数量
        buttonLoading: false,
    },
    onLoad: function (options) {
        if (options.uid) {
            //页面分享携带uid绑定关系
            this.redirect_login(options.uid);
        }
    },
    onShow() {
        this.getCartList();
    },
    //获取购物车列表
    getCartList() {
        this.request(
            {
                url: '/api/cart/index',
                hideFailToast: true,
            },
            res => {
                //格式化res.data
                res.data.forEach(item => {
                    let flag = true;
                    let _childrenCheckArr = [];
                    item.cart_info.forEach((child, index) => {
                        child.selected === 1 ? _childrenCheckArr.push(index) : (flag = false);
                    });
                    item.check = flag;
                    item.cart_info.map(child => {
                        return (child.product_img = child.product_img + '!img_200');
                    });
                });
                this.setData({
                    list: res.data,
                    chooseAll: res.selected_status === 0 ? false : true,
                    finished: true,
                    loading: false,
                    empty: res.data.length === 0,
                });
                if (res.selected_status === 1) {
                    this.setData({ totalPrice: res.total.total_price, checkNum: res.total.count });
                    getApp().globalData.cartCheckNum = res.total.count;
                } else {
                    this.calculation();
                }
            },
            () => {
                this.setData({ list: [], chooseAll: false, finished: true, loading: false, empty: true });
            }
        );
    },
    //删除提示
    async del(e) {
        const { index, cart_id, childrenindex, all } = e.currentTarget.dataset;
        try {
            await wx.$dialog.confirm({
                title: '提示',
                message: '您确定删除吗？',
                theme: 'round-button',
            });
        } catch (error) {
            return;
        }
        let cart_ids = [];
        if (all) {
            //供应商购物车删除
            this.data.list[index].cart_info.forEach(item => {
                cart_ids.push(item.cart_id);
            });
        } else {
            //单个产品删除
            cart_ids.push(cart_id);
        }
        this.confirmDel(cart_ids, all, index, childrenindex);
    },
    //确认删除购物车
    confirmDel(cart_ids, all, index, childrenIndex) {
        this.request(
            {
                url: '/api/cart/cartDelete',
                method: 'POST',
                data: { cart_ids },
            },
            () => {
                wx.showToast({
                    title: '删除成功',
                    icon: 'success',
                });
                let { list } = this.data;
                if (all) {
                    //供应商商品全部删除
                    list.splice(index, 1);
                    this.setData({ list, empty: list.length === 0 });
                    this.checkAllChoose();
                    this.calculation();
                    return;
                }
                //供应商内单个商品删除
                list[index].cart_info.splice(childrenIndex, 1);
                if (list[index].cart_info.length === 0) {
                    list.splice(index, 1);
                } else {
                    let check = true;
                    list[index].cart_info.forEach(item => {
                        if (item.selected === 0) check = false;
                    });
                    list[index].check = check;
                }
                this.setData({ list, empty: list.length === 0 });
                this.checkAllChoose();
                this.calculation();
            }
        );
    },
    //全选单个供应商内商品
    onsupplierChoose(e) {
        const { index } = e.currentTarget.dataset;
        const { list } = this.data;
        this.request(
            {
                url: '/api/cart/selectCart',
                method: 'POST',
                data: { cart_id: '1', supplier_id: list[index].supplier_id },
            },
            () => {
                let isCheck = !list[index].check;
                let newCart_info = list[index].cart_info;
                newCart_info.forEach(item => {
                    isCheck ? (item.selected = 1) : (item.selected = 0);
                });
                this.setData({
                    ['list[' + index + '].check']: isCheck,
                    ['list[' + index + '].cart_info']: newCart_info,
                });
                this.checkAllChoose();
                this.calculation();
            },
            () => {
                wx.showToast({
                    title: '选中失败',
                    icon: 'error',
                });
            }
        );
    },
    //供应商子项却换选中
    onFlowerChange(e) {
        const { index, childrenindex } = e.currentTarget.dataset;
        const { list } = this.data;

        this.request(
            {
                url: '/api/cart/selectCart',
                method: 'POST',
                data: { cart_id: list[index].cart_info[childrenindex].cart_id },
            },
            () => {
                let selectValue = list[index].cart_info[childrenindex].selected;
                selectValue = selectValue === 0 ? 1 : 0;
                this.setData({
                    ['list[' + index + '].cart_info[' + childrenindex + '].selected']: selectValue,
                });

                let isCheck = true;

                if (selectValue === 1) {
                    list[index].cart_info.forEach(item => {
                        if (item.selected === 0) isCheck = false;
                    });
                } else {
                    isCheck = false;
                }
                this.setData({
                    ['list[' + index + '].check']: isCheck,
                });
                this.checkAllChoose();
                this.calculation();
            },
            () => {
                wx.showToast({
                    title: '选中失败',
                    icon: 'error',
                });
            }
        );
    },
    //数量加
    numAdd(e) {
        const { childrenindex, index } = e.currentTarget.dataset;
        const { cart_id } = this.data.list[index].cart_info[childrenindex];
        this.numsEdit(cart_id, 'add', childrenindex, index);
    },
    //数量减
    numCut(e) {
        const { childrenindex, index } = e.currentTarget.dataset;
        const { cart_id } = this.data.list[index].cart_info[childrenindex];
        this.numsEdit(cart_id, 'reduce', childrenindex, index);
    },
    //数量加减操作
    numsEdit(cart_id, cart_type, childrenindex, index) {
        this.request(
            {
                url: '/api/cart/addCart',
                method: 'POST',
                loadingTip: '处理中',
                data: { cart_id, cart_type },
            },
            () => {
                let { product_number } = this.data.list[index].cart_info[childrenindex];
                cart_type === 'add' ? product_number++ : product_number--;
                this.setData({
                    ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: product_number,
                });
                this.calculation();
            }
        );
    },
    //修改数量
    updateNums(e) {
        const { childrenindex, index } = e.currentTarget.dataset;
        let { value } = e.detail;
        const originNums = this.data.list[index].cart_info[childrenindex].product_number; //原数量，操作失败数量恢复
        const stock = this.data.list[index].cart_info[childrenindex].sku; //库存

        if (value === originNums) {
            /**先赋值成不同的值，输入框的value才会改变 */
            this.setData({
                ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: value,
            });
            this.delay(() => {
                this.setData({
                    ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: originNums,
                });
            }, 0);
            return;
        }

        if (value > stock) {
            //库存不足
            value = stock;
            wx.showToast({
                title: '您输入的数量超过剩余库存最大值，已为您自动设置为最大库存数量',
                icon: 'none',
                duration: 3000,
            });
        }

        this.request(
            {
                url: '/api/cart/cartSku',
                method: 'POST',
                data: {
                    cart_id: this.data.list[index].cart_info[childrenindex].cart_id,
                    nums: value,
                },
            },
            () => {
                this.setData({
                    ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: value,
                });
                this.calculation();
            },
            () => {
                /**先赋值一边，输入框的value才会改变 */
                this.setData({
                    ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: value,
                });
                this.delay(() => {
                    this.setData({
                        ['list[' + index + '].cart_info[' + childrenindex + '].product_number']: originNums,
                    });
                }, 0);
            }
        );
    },
    //检查全选
    checkAllChoose() {
        const { list } = this.data;
        let chooseAll = list.every(item => {
            return item.check === true;
        });
        this.setData({ chooseAll });
    },
    //点击全选全不选
    onChooseAllChange({ detail }) {
        this.request(
            {
                url: '/api/cart/selected',
                method: 'POST',
            },
            () => {
                const { list } = this.data;
                const selectedValue = detail ? 1 : 0;
                list.forEach(item => {
                    item.check = detail;
                    item.cart_info.forEach(child => {
                        child.selected = selectedValue;
                    });
                });
                this.setData({ list, chooseAll: detail });
                this.calculation();
            },
            () => {
                wx.showToast({
                    title: '全选失败',
                    icon: 'error',
                });
            }
        );
    },
    //计算价格
    calculation() {
        let totalPrice = 0;
        let checkNum = 0;
        this.data.list.forEach(item => {
            item.cart_info.forEach(child => {
                if (child.selected === 1) {
                    totalPrice += child.product_price * child.product_number;
                    totalPrice = Number(totalPrice.toFixed(2));
                    checkNum += child.product_number;
                }
            });
        });
        this.setData({ totalPrice: totalPrice, checkNum });
        this.setCartCheckNum(checkNum);
    },
    //点击结算
    async onSubmit() {
        this.setData({ buttonLoading: true });

        /**判断是否授权手机号码 */
        if (this.data.userInfo.audit === 0) {
            this.setData({ buttonLoading: false });
            return wx.$dialog.alert({
                title: '提示',
                message: '您还未授权手机号，即将前往个人中心，请点击授权按钮授权手机号。',
                theme: 'round-button',
                beforeClose: action =>
                    new Promise(resolve => {
                        resolve(true);
                        wx.switchTab({
                            url: '/pages/my/index',
                        });
                    }),
            });
        }

        /**判断是否已实名认证 */
        if (this.data.userInfo.verify === 0) {
            this.setData({ buttonLoading: false });
            return wx.$dialog.confirm({
                title: '提示',
                message: '您还未完善您的姓名，请完善后再来下单。',
                confirmButtonText: '前往',
                cancelButtonText: '关闭',
                theme: 'round-button',
                beforeClose: action =>
                    new Promise(resolve => {
                        if (action === 'confirm') {
                            resolve(true);
                            wx.navigateTo({
                                url: '/pages/real_name/index',
                            });
                        } else {
                            resolve(true);
                        }
                    }),
            });
        }

        const { list } = this.data;
        let flag = false;
        verification();

        function verification() {
            for (let i = 0; i < list.length; i++) {
                for (let j = 0; j < list[i].cart_info.length; j++) {
                    if (list[i].cart_info[j].selected === 1) return (flag = true); //跳出函数
                }
            }
        }

        if (!flag) {
            wx.showToast({
                title: '请至少选择一件商品',
                icon: 'none',
            });
            return this.setData({ buttonLoading: false });
        }

        /**验证是否有收货地址 */
        this.request(
            {
                url: '/api/user/addr/index',
                data: { limit: 1 },
            },
            res => {
                if (res.data.length === 0) {
                    return wx.$dialog
                        .confirm({
                            title: '提示',
                            message: '您还没有设置收货地址，是否前往设置？',
                        })
                        .then(() => {
                            return wx.navigateTo({
                                url: '/pages/address_manage/index?choose=true',
                            });
                        })
                        .finally(() => {
                            this.setData({ buttonLoading: false });
                        });
                }
                this.confirmOrder();
            }
        );
    },
    /**确认结算订单 */
    confirmOrder() {
        this.request(
            {
                url: '/api/cart/cart',
                hideToastInclude: [10099],
            },
            result => {
                // if (result.data.freight_list.length === 0) {
                //     this.setData({ buttonLoading: false })
                //     return wx.showModal({
                //         content: '达不到起订数、或该区域不在发货范围',
                //         confirmColor: '#188075',
                //         showCancel: false
                //     })
                // }
                const { list } = this.data;
                //前端生成订单商品信息
                let orderGoods = [];
                list.forEach((supplier, current) => {
                    const index = supplier.cart_info.findIndex(item => {
                        return item.selected === 1;
                    });
                    if (index >= 0) {
                        let supplierInfo = {
                            logo: supplier.logo,
                            title: supplier.title,
                        };
                        let goods = supplier.cart_info.filter(cart => {
                            return cart.selected === 1;
                        });
                        orderGoods.push({ supplierInfo, goods });
                    }
                });
                //计算预估重量
                let weightTotal = 0;
                orderGoods.forEach(item => {
                    item.goods.forEach(good => {
                        let weight = (Number(good.weight) * good.product_number).toFixed(2);
                        weightTotal = Number(weight) + weightTotal;
                    });
                });
                wx.navigateTo({
                    url: '/pages/settlement/index',
                    success: res => {
                        res.eventChannel.emit('acceptDataFromOpenerPage', {
                            data: {
                                orderInfo: result.data,
                                orderGoods,
                                weightTotal: weightTotal.toFixed(2),
                            },
                        });
                    },
                });
                this.setData({ buttonLoading: false });
            },
            result => {
                this.setData({ buttonLoading: false });
                /** 提示前往欠款明细*/
                if (result.code === 10099) {
                    wx.showModal({
                        content: result.msg || '有欠款，请先支付欠款后再下单',
                        confirmColor: '#188075',
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({ url: '/pages/arrears/index' });
                            }
                        },
                    });
                }
            }
        );
    },
    /**前往供应商详情 */
    tosupplierDetail(e) {
        const { supplier_id } = e.currentTarget.dataset;
        wx.navigateTo({ url: `/pages/supplier_detail/index?id=${supplier_id}` });
    },
    /**前往商品详情 */
    toGoodDetail(e) {
        const { product_id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/good_detail/index?id=${product_id}`,
        });
    },
    //设置tabbar组件的购物车选中数量(选中\非选中商品或供应商切换时)
    setCartCheckNum(num) {
        let tabbar = this.selectComponent('#tabbar'); // 页面获取自定义组件实例
        tabbar.setCartCheckNum(num); // 通过实例调用组件事件
        getApp().globalData.cartCheckNum = num;
    },
    refresh() {},
    //点击分享
    onShareAppMessage() {
        let options = '/pages/cart/index';
        if (this.data.userInfo) options += `?uid=${this.data.userInfo.uid}`;
        return {
            path: options,
        };
    },
    // onHide: function() {
    //     this.delay(() => {
    //         this.setData({ list: [], chooseAll: false, finished: false, loading: true, empty: true })
    //     }, 300)
    // }
});
